/**
 * @author taowei20061122@163.com
 *
 * 2013-9-4 上午10:03:40
 */
package etl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Properties;

/**
 * @author taowei20061122@163.com
 * 
 *         2013-9-4 上午10:03:40
 */
public class ReadAccessDb {
	/**
	 * TODO : 读取文件access
	 * 
	 * @param filePath
	 * @return
	 * @throws ClassNotFoundException
	 */
	public static List<Map> readFileAccessDb(String filePath) {
		List<Map> maplist = new ArrayList();
		Properties prop = new Properties();
		prop.put("charSet", "gb2312"); // 这里是解决中文乱码
		prop.put("user", "");
		prop.put("password", "");
		String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ="
				+ filePath; // 文件地址
		
		Connection conn = null;
//		PreparedStatement ps = null;
		Statement stmt = null;
		ResultSet rs = null;
		BufferedWriter localLogger = null;;
		try {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			conn = DriverManager.getConnection(url, prop);
			stmt = (Statement) conn.createStatement();

			rs = stmt.executeQuery("select * from Chinese");
			ResultSetMetaData metaData = rs.getMetaData();
			int columnCount = metaData.getColumnCount();
			
			try {
				File f = new File("");
				if(!f.exists()){
					f.mkdirs();
				}
				localLogger = new BufferedWriter(new FileWriter("d:/tw/....txt"));
				for (int i = 0; i < columnCount; i++) {
					if(0==i) {
						localLogger.write(metaData.getColumnLabel(i+1));
					}else {
						localLogger.write(","+metaData.getColumnLabel(i+1));
					}
				}
				localLogger.newLine();
				localLogger.flush();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			while (rs.next()) {
//				Map map = new HashMap();
				for (int i = 1; i <= columnCount; i++) {
//					String columnName = metaData.getColumnName(i); // 列名
//					String columnValue = rs.getString(i);
//					map.put(columnName, columnValue);
					if(1==i) {
						localLogger.write(rs.getString(1)==null?"":rs.getString(1));
					}else {
						localLogger.write(","+rs.getString(i)==null?"":rs.getString(i));
					}
				}
				localLogger.newLine();
				localLogger.flush();
//				maplist.add(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return maplist;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ReadAccessDb.readFileAccessDb("");
	}

}
